package com.yao.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author YAO
 * @create 2021-05-07 21:05
 */
@WebServlet(name = "SessionServlet",value = "/sessionServlet")
public class SessionServlet extends BaseServlet{

    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建和获取session会话对象
        HttpSession session = req.getSession();
        // 判断当前session会话是否是新创建出来的
        boolean isNew = session.isNew();
        // 获取session会话的唯一标识id
        String id = session.getId();

        resp.getWriter().write("得到的session,它的id是：" + id + "<br/>");
        resp.getWriter().write("这个session是否是新创建的：" + isNew + "<br/>");
    }

    /**
     * 往session中保存数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void setAttr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1","value1");
        resp.getWriter().write("已经往session中保存了数据");
    }

    /**
     * 往session中获取数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getAttr(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object key1 = req.getSession().getAttribute("key1");
        resp.getWriter().write("从session中获取key1的数据的是：" + key1.toString());
    }

    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Session的默认超时时长
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();

        resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + "秒");

    }

    protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先获取Session对象
        HttpSession session = req.getSession();
        //设置当前session 3秒后超时
        session.setMaxInactiveInterval(3);
        resp.getWriter().write("当前session已经设置为3秒后超时");

    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先获取Session对象
        HttpSession session = req.getSession();
        //设置当前session 马上超时
        session.invalidate();
        resp.getWriter().write("当前session已经设置为超时（无效）");

    }

}
